package com.meisiabc.app.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meisiabc.app.repository.db.constant.ScheduleStatus;
import com.meisiabc.app.repository.db.entity.*;
import com.meisiabc.app.repository.db.manager.*;
import com.meisiabc.support.wechat.WechatClient;
import com.meisiabc.utils.DateTimeUtil;
import com.meisiabc.utils.RandomNumeric;
import com.meisiabc.utils.Verify;
import com.meisiabc.utils.math.BigDecimalUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
public class RecommenderService {
    @Autowired
    private FreeAuditionManager freeAuditionManager;
    @Autowired
    private TrylistenmanageManager trylistenmanageManager;
    @Autowired
    private RecommendMsgManager recommendMsgManager;
    @Autowired
    private StudentManager studentManager;
    @Autowired
    private PurchaseCourseManager purchaseCourseManager;
    @Autowired
    private WechatClient wechatClient;
    @Autowired
    private CurriculumScheduleManager curriculumScheduleManager;

    public JSONObject recommenderList(String mobile) {
        Student student = studentManager.selectByMobile(mobile);
        if (student == null) {
            return new JSONObject().fluentPut("totalTry", 0)
                    .fluentPut("totalPay", 0)
                    .fluentPut("totalAward", 0)
                    .fluentPut("totalAwardTime", 0)
                    .fluentPut("list", Collections.emptyList());
        }

        int totalRecommend = freeAuditionManager.count(new QueryWrapper<FreeAudition>().eq("recommend_id", student.getStudentId()));

        List<JSONObject> list = new ArrayList<>();
        int totalPay = 0;
        int totalTry = 0;
        int totalAward = 0;
        BigDecimal totalAwardTime = BigDecimal.ZERO;

        List<RecommendMsg> records = recommendMsgManager.list(new QueryWrapper<RecommendMsg>().eq("recommender_id", student.getStudentId()));
        for (RecommendMsg record : records) {
            int payCount = purchaseCourseManager.count(new QueryWrapper<PurchaseCourse>().eq("student_id", record.getNewStudentId()).eq("is_pay", "已支付"));
            int tryListen = trylistenmanageManager.count(new QueryWrapper<Trylistenmanage>().eq("student_id", record.getNewStudentId()));
            boolean shi_ting_State = tryListen > 0 ? true : false;
            boolean pay_State = payCount > 0 ? true : false;
            boolean award_State = "已发放".equals(record.getJiangStatus());

            list.add(new JSONObject()
                    .fluentPut("newStudentPhone", record.getNewStudentPhone())
                    .fluentPut("recommendDate", record.getRecommendDate())
                    .fluentPut("shi_ting_State", shi_ting_State)
                    .fluentPut("pay_State", pay_State)
                    .fluentPut("award_State", award_State));

            if (record.getRecommendAward() != null) {
                totalAwardTime = BigDecimalUtils.cal(totalAwardTime).plus(record.getRecommendAward()).result();
            }

            if (shi_ting_State) {
                totalTry++;
            }

            if (pay_State) {
                totalPay++;
            }

            if (award_State) {
                totalAward++;
            }
        }

        return new JSONObject()
                .fluentPut("totalRecommend", totalRecommend)
                .fluentPut("totalTry", totalTry)
                .fluentPut("totalPay", totalPay)
                .fluentPut("totalAward", totalAward)
                .fluentPut("totalAwardTime", totalAwardTime.toPlainString())
                .fluentPut("list", list);
    }


    public JSONObject poster(String mobile, DateTime now) {
        Student student = studentManager.selectByMobile(mobile);
        if (student == null) {
            return new JSONObject().fluentPut("enName", "")
                    .fluentPut("total_days", 0)
                    .fluentPut("total_lesson", 0)
                    .fluentPut("percent", 100);
        }

        int totalLessonCompleted = 0;
        List<PurchaseCourse> courses = purchaseCourseManager.selectByStudentId(student.getStudentId());
        if (courses != null) {
            for (PurchaseCourse course : courses) {
                totalLessonCompleted += hoursCompleted(course.getUniqueid());
            }
        }

        return new JSONObject().fluentPut("enName", student.getEnName())
                .fluentPut("total_days", DateTimeUtil.daysbetweenHuman(new DateTime(student.getCreateTime()), now))
                .fluentPut("total_lesson", totalLessonCompleted)
                .fluentPut("percent", RandomNumeric.getInstance().random(85, 98));
    }

    private int hoursCompleted(String courseId) {
        int result = 0;
        List<CurriculumSchedule> schedules = curriculumScheduleManager.list(new QueryWrapper<CurriculumSchedule>().eq("purchase_course_id", courseId).in("state", Arrays.asList(String.valueOf(ScheduleStatus.S7.getCode()), String.valueOf(ScheduleStatus.S3.getCode()))));
        for (CurriculumSchedule schedule : schedules) {
            result += schedule.getClassLength();
        }

        return result;
    }

    public String getRecommendId(String mobile) {
        Student student = studentManager.selectByMobile(mobile);
        if (student == null) {
            return "";
        }

        return student.getStudentId();
    }

    public InputStream wechatQrcode(String mobile) {
        InputStream result = wechatClient.qrCodes("pages/bespeak/bespeak", mobile);
        Verify.notNull(result, "生成小程序二维码失败");
        return result;
    }
}
